package com.udi.project.business.activate.thread;


import com.udi.project.business.activate.daomain.ActivateCode;
import com.udi.project.business.activate.detect.DetectTime;
import com.udi.project.business.activate.mapper.ActivateCodeMapper;
import com.udi.project.business.utils.RSA.RSAUtils;
import com.udi.project.business.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.crypto.BadPaddingException;
import java.security.spec.InvalidKeySpecException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * @author Admin
 * 有效期验证 每天 24点验证有效期一次
 *定时
 */
@Component                //实例化
@Configurable             //注入bean
@EnableScheduling         //开启计划任务
@Slf4j
public class ActivateCodeThread {

    /** RSA解密*/
    @Autowired
    private RSAUtils rsaUtils;
    @Autowired
    private ActivateCodeMapper activateCodeMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private DetectTime detectTime;

    //cron = "0 0 0 * * ?"
    //cron = "*/5 * * * * ?"
    /** {秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}*/
    @Scheduled(cron = "0 0 0 * * ?")
    public void reom() throws Exception{

        /** 系统时间校验*/
        if(detectTime.detec()){
            String keyJson = null;
            ActivateCode activateCode = activateCodeMapper.selectEffectiveDate();

            try {
                keyJson =  rsaUtils.privateDecrypt(activateCode.getValid_period(),activateCode.getValid_privateKey());
            }catch (Exception e){
                e.printStackTrace();
            }



            SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date begin=dfs.parse(keyJson);
            Date end = new Date();
            Date currentTime = dfs.parse(dfs.format(end));
            LocalDate localDate1 = ZonedDateTime.ofInstant(begin.toInstant(), ZoneId.systemDefault()).toLocalDate();
            LocalDate localDate2 = ZonedDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault()).toLocalDate();

            System.out.println("------------------------定时激活码检查器已运行------------------当前时间为："+currentTime);
            /** 产品到期时间与本地时间对比*/
            if(localDate1.isEqual(localDate2)){
                /** 产品到期冻结所有用户 并启动拦截器 转发页面至产品激活码页面*/
                activateCodeMapper.freezeUser();
                redisUtils.set("period","yes");
            }else {redisUtils.set("period","no");}
        }else {return;}
    }
}
